package main

import (
	"fmt"
	"io"
	"net"
	"time"
	"zinx/znet"
)

func main() {
	// 这里去测试发送请求到server
	fmt.Println("client start...")

	time.Sleep(1 * time.Second)

	conn, err := net.Dial("tcp", "127.0.0.1:8999")
	if err != nil {
		fmt.Println("client start error: ", err)
		return
	}

	for {
		// 发送封包的消息
		dp := znet.NewDataPack()
		binaryMsg, err := dp.Pack(znet.NewMsgPackage(1, []byte("Zinx client1 V0.7 client test message")))
		if err != nil {
			fmt.Println("Pack error ", err)
			return
		}
		fmt.Println(string(binaryMsg))
		if _, err := conn.Write(binaryMsg); err != nil {
			fmt.Println("write error ", err)
			return
		}

		// 服务器回复我们一个message数据，解包
		// 先读取流中的head, 得到id 和 datalen
		binaryHead := make([]byte, dp.GetHeadLen())
		if _, err := io.ReadFull(conn, binaryHead); err != nil {
			fmt.Println("read head error", err)
			return
		}
		msgHead, err := dp.Unpack(binaryHead)
		if err != nil {
			fmt.Println("client unpack msg head error ", err)
		}
		if msgHead.GetDataLen() > 0 {
			// 再根据dataLen 进行第二次读取，将data读出来
			msg := msgHead.(*znet.Message)
			msg.Data = make([]byte, msg.GetDataLen())
			if _, err := io.ReadFull(conn, msg.Data); err != nil {
				fmt.Println("client read msg data error ", err)
				return
			}

			fmt.Println("recrv msg data ...", string(msg.GetData()))
			fmt.Println("recrv head data ...", string(msgHead.GetData()))
		}

		// cup 阻塞下
		time.Sleep(1 * time.Second)
	}
}
